package com.top10.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.top10.bean.ResponseBean;
import com.top10.common.DatabaseConst;
import com.top10.entity.Address;
import com.top10.entity.Express;
import com.top10.entity.Shop;
import com.top10.service.AddressService;
import com.top10.service.IExpressService;
import com.top10.service.IShopService;
import com.top10.utils.DistanceUtil;
import com.top10.utils.ExpressPriceUtil;
import com.top10.utils.HttpUtils;
import com.top10.utils.Ture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/manager/express")
public class UserAddressController {

	private static final String key = "fCaySSyf5709";
	private static final String customer = "C049A798F3EEEEE3FE606A194A5AA6B0";
	private static final String queryUrl = "http://poll.kuaidi100.com/poll/query.do";
	private static final String autonumberUrl = "http://www.kuaidi100.com/autonumber/auto";


	@Autowired
	IExpressService iExpressService;
	@Autowired
	AddressService addressService;
	@Autowired
	IShopService shopService;

	/**
	 * 获取快递费
	 */
	@RequestMapping("/getexpressprice")
	public ResponseBean getExpressPrice(String province, String city, String district, String shop_uuid) throws Exception {
		String[] shopUuidsArr = shop_uuid.split(",");
		String query_where = DistanceUtil.fullAddress(province, city, district);
		List<Express> expressList1 = new ArrayList<>();
		for (String shop_uuid1 : shopUuidsArr) {

			Express express1 = new Express();
			List<Express> expressList = iExpressService.selectList(new EntityWrapper<Express>()
					.eq("shop_uuid", shop_uuid1).eq("isdeleted", DatabaseConst.IS_DELETED_NO));
			/*if (query_where == null || "".equals(query_where)) {
				for (Express express : expressList) {
					express.setPrice(0);
				}
				return ResponseBean.createSuccess("包邮");
			}*/
			// 根据邮寄地址的省市区信息查找到对应的经纬度
			Address address = addressService.selectByFullName(query_where);
			// 根据店铺的UUID查询店铺的省市区信息
			Shop shop = shopService.selectByUuid(shop_uuid1);
			// 根据店铺的省市区信息查找到对应的经纬度信息
			String shopProvince = shop.getProvince();
			String shopCity = shop.getCity();
			String shopDistrict = shop.getDistrict();
			String fullName = DistanceUtil.fullAddress(shopProvince, shopCity, shopDistrict);


			/*String d=fullName1.substring(fullName1.length()-1);
             if(d.equals(",")){
				  fullName=fullName1.substring(0,fullName1.length()-1);
			 }else{
             	 fullName=fullName1;
			 }*/

			Address shopAddress = addressService.selectByFullName(fullName);
			for (Express express : expressList) {
				int price = ExpressPriceUtil.calcPrice(address, shopAddress, express);
				express.setPrice(price);
			}
			Integer someThing = null;
			for (int i = 0; i < expressList.size(); i++) {
				if (someThing == null) {
					someThing = expressList.get(i).getPrice();
					express1 = expressList.get(i);
				}
				Integer A = expressList.get(i).getPrice();
				if (someThing > A) {
					someThing = expressList.get(i).getPrice();
					express1 = expressList.get(i);
				}
			}
			expressList1.add(express1);
		}
		return ResponseBean.createSuccess("获取邮费信息成功").addData("express", expressList1);
	}
	/*
	 */

	/**
	 * 获取快递物流信息
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getwuliu")
	public ResponseBean getAutoNumber(String num) throws Exception {
		List<Map<String, Object>> resultDataList = null;
		Map<String, Object> resultData = null;
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> result = new HashMap<>();
		StringBuffer param = null;
		StringBuffer sb = new StringBuffer();
		StringBuffer sb2 = null;
		boolean isOk = false;
		try {
			if (num == null || "".equals(num.trim())) {
				return ResponseBean.createError("快递单号不能为空");
			} else {
				sb.append("num=" + num);
				sb.append("&");
				sb.append("key=" + key);
				resultDataList = mapper.readValue(HttpUtils.doGet(autonumberUrl, sb.toString(), null), List.class);
				for (Map<String, Object> map : resultDataList) {
					if (!isOk) {
						param = new StringBuffer();
						sb2 = new StringBuffer();
						param.append("{");
						param.append("\"com\":\"" + map.get("comCode") + "\"");
						param.append(",\"num\":\"" + num + "\"");
						param.append("}");
						sb2.append("customer=" + customer);
						sb2.append("&");
						sb2.append("sign=" + new Ture().getMD5(param + key + customer));
						sb2.append("&");
						sb2.append("param=" + param);
						resultData = mapper.readValue(HttpUtils.doPost(queryUrl, sb2.toString(), null), Map.class);
						if (resultData != null && !resultData.containsKey("returnCode")) {
							isOk = true;
						}
					}
				}
				if (resultData != null) {
					if (resultData.containsKey("returnCode")) {
						Object msg = resultData.get("message");
						return ResponseBean.createError(msg.toString());
					} else {
						return ResponseBean.createSuccess("获取成功").addData("data", resultData);
					}
				} else {
					return ResponseBean.createError("快递单号不正确");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseBean.createError("获取快递单号所属公司失败：" + e.getMessage());
		}
	}
}

